package com.scqkzqtz.basesdk.utils;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.os.Environment;
import android.text.TextUtils;
import android.view.View;
import android.widget.Toast;

import java.io.File;
import java.io.FileOutputStream;
import java.util.HashMap;
import java.util.UUID;

import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.tencent.qq.QQ;
import cn.sharesdk.tencent.qzone.QZone;
import cn.sharesdk.wechat.friends.Wechat;
import cn.sharesdk.wechat.moments.WechatMoments;

/**
 * 分享工具类
 * Created by michael on 2017/12/13.
 */

public class ShareUtil {

    private ShareWindow shareWindow;

    private ShareUtil() {

    }

    private static ShareUtil instance;

    public static ShareUtil getInstance() {
        if (instance == null) {
            synchronized (ShareUtil.class) {
                if (instance == null)
                    instance = new ShareUtil();
            }
        }

        return instance;
    }

    public interface OnShareCompleteListener {
        void onComplete();
    }

    private OnShareCompleteListener mOnShareCompleteListener;

    public void setOnShareCompleteListener(OnShareCompleteListener onShareCompleteListener) {
        this.mOnShareCompleteListener = onShareCompleteListener;
    }

    /**
     * 显示分享弹框
     * @param activity
     * @param view 根布局
     * @param shareEntity
     */
    public void share(final Activity activity, View view, final ShareEntity shareEntity) {
        if (shareWindow == null)
            shareWindow = new ShareWindow(activity);
        shareWindow.show(view);
        shareWindow.setOnShareWindowShowListener(new ShareWindow.OnShareWindowShowListener() {
            @Override
            public void show(int position) {
                switch (position) {
                    case 0:
                        shareToPlatform(activity, Wechat.NAME, shareEntity);
                        break;
                    case 1:
                        shareToPlatform(activity, WechatMoments.NAME, shareEntity);
                        break;
                    case 2:
                        shareToPlatform(activity, QQ.NAME,shareEntity);
                        break;
                    case 3:
                        shareToPlatform(activity, QZone.NAME, shareEntity);
                        break;
                }
            }
        });
    }

    /**
     * 显示分享弹框
     * @param activity
     * @param view 根布局
     */
    public void shareWindowView(final Activity activity, final View view) {
        if (shareWindow == null)
            shareWindow = new ShareWindow(activity);
        shareWindow.show(view);
        shareWindow.setOnShareWindowShowListener(new ShareWindow.OnShareWindowShowListener() {
            @Override
            public void show(int position) {
                switch (position) {
                    case 0:
                        shareWindowView(activity, Wechat.NAME);
                        break;
                    case 1:
                        shareWindowView(activity, WechatMoments.NAME);
                        break;
                    case 2:
                        shareWindowView(activity, QQ.NAME);
                        break;
                    case 3:
                        shareWindowView(activity, QZone.NAME);
                        break;
                }
            }
        });
    }

    /**
     * 截屏分享
     *
     * @param activity
     * @param platform
     */
    public void shareWindowView(Activity activity, String platform) {
        Platform platform1 = ShareSDK.getPlatform(platform);
        View windowView = activity.getWindow().getDecorView();
        Bitmap bitmap = convertViewToBitmap(windowView);
        String imagePath = saveBitmap(activity, bitmap);
        Platform.ShareParams sp = new Platform.ShareParams();
        if (Wechat.NAME.equals(platform) || WechatMoments.NAME.equals(platform)) {
            sp.setImageData(bitmap);
        } else if (QQ.NAME.equals(platform) || QZone.NAME.equals(platform)) {
            sp.setImagePath(imagePath);
        }

        sp.setShareType(Platform.SHARE_IMAGE);
        platform1.share(sp);
    }

    /**
     * 将视图转化为bitmap
     *
     * @param view
     * @return Bitmap
     */
    public static Bitmap convertViewToBitmap(View view) {
        Bitmap bitmap = Bitmap.createBitmap(view.getWidth(), view.getHeight(),
                Bitmap.Config.RGB_565);
        Canvas canvas = new Canvas(bitmap);
        view.draw(canvas);
        return bitmap;
    }

    /**
     * 随机生产文件名
     *
     * @return String
     */
    private static String generateFileName() {
        return UUID.randomUUID().toString();
    }

    /**
     * 保存bitmap到本地
     *
     * @param context
     * @param mBitmap
     * @return String
     */
    public static String saveBitmap(Context context, Bitmap mBitmap) {
        String savePath;
        File filePic;
        String SD_PATH = "/sdcard/share/pic/";
        String IN_PATH = "/share/pic/";
        if (Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED)) {
            savePath = SD_PATH;
        } else {
            savePath = context.getApplicationContext().getFilesDir()
                    .getAbsolutePath()
                    + IN_PATH;
        }
        try {
            filePic = new File(savePath + generateFileName() + ".jpg");
            if (!filePic.exists()) {
                filePic.getParentFile().mkdirs();
                filePic.createNewFile();
            }
            FileOutputStream fos = new FileOutputStream(filePic);
            mBitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            fos.flush();
            fos.close();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }

        return filePic.getAbsolutePath();
    }

    /**
     * 检测外部存储是否可用
     *
     * @return boolean
     */
    public static boolean checkSDCardAvailable() {
        return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
    }

    /**
     * 分享至特定平台
     *
     * @param platform 分享平台
     */
    private void shareToPlatform(final Activity activity, String platform, ShareEntity shareEntity) {
        Platform platform1 = ShareSDK.getPlatform(platform);
        if (!platform1.isClientValid()) {
            Toast.makeText(activity, "您尚未安装" + platform1.getName() + "!",Toast.LENGTH_SHORT).show();
            return;
        }

        String url = shareEntity.getUrl();
        String title = shareEntity.getTitle();
        String content = shareEntity.getContent();
        String imageUrl = shareEntity.getImageUrl();

        Platform.ShareParams sp = new Platform.ShareParams();
        sp.setUrl(TextUtils.isEmpty(url) ? "" : url);
        sp.setSite(TextUtils.isEmpty(url) ? "" : url);
        sp.setSiteUrl(TextUtils.isEmpty(url) ? "" : url);
        sp.setTitleUrl(TextUtils.isEmpty(url) ? "" : url);
        sp.setTitle(TextUtils.isEmpty(title) ? "" : title);
        sp.setText(TextUtils.isEmpty(content) ? "" : content);
        sp.setImageUrl(TextUtils.isEmpty(imageUrl) ? "" : imageUrl);

        sp.setShareType(Platform.SHARE_WEBPAGE);
        platform1.setPlatformActionListener(new PlatformActionListener() {
            public void onError(Platform arg0, int arg1, Throwable arg2) {
                //失败的回调，arg:平台对象，arg1:表示当前的动作，arg2:异常信息
                Toast.makeText(activity, arg2.getMessage(),Toast.LENGTH_SHORT).show();
            }

            public void onComplete(Platform arg0, int arg1, HashMap<String, Object> arg2) {
                //分享成功的回调
                if (mOnShareCompleteListener != null)
                    mOnShareCompleteListener.onComplete();
            }

            public void onCancel(Platform arg0, int arg1) {
                //取消分享的回调
                if (mOnShareCompleteListener != null)
                    mOnShareCompleteListener.onComplete();
            }
        });
        platform1.share(sp);
    }

}
